'use strict';
const uniID = require('uni-id')
const {
    Controller
} = require('uni-cloud-router')
const appid = "wx3bd95dff819ac8ce"
const appsecret = "9e87c365f68f4ace94ebc05a2b50b408"
const Avatar='https://img.cdn.aliyun.dcloud.net.cn/uni-app/uniCloud/unicloudlogo.png'
module.exports = class LoginController extends Controller {
	//微信登录
    async weixing() {
		const params=this.ctx.data
		const  res = await uniID.loginByWeixin(params);
		if(res.userInfo && res.userInfo.token){
			delete(res.userInfo.token)
		}
        return res
    }
	//微信取得用户信息
	async getUserInfo(){
		const params=this.ctx.data
		const {code}=params
		let url=`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${appsecret}&code=${code}&grant_type=authorization_code`
		const  {status,data} = await this.curl(url,{dataType:'json'})
		if(status !== 200){
			this.throw('WX_OAUTH_ACCESS_TOKEN','取得access_token失败')
		}
		const {openid,access_token}=data
		url=`https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}`
		const res =await this.curl(url,{dataType:'json'})
		if(res.status !== 200){
			this.throw('WX_OAUTH_USER_INFO','取得userinfo失败')
		}
		return res.data
	}
	//登录或注册
	async registerOrLogin(){
		const params=this.ctx.data
		let res= await this.db.collection('uni-id-users')
			.where({username: params.username}).count();
			
		if(res.total===0){
			const nickname=params.username
			const avatar=Avatar
			await uniID.register({...params,nickname,avatar});
		}
		
		res = await uniID.login({
			...params,
			// 不指定queryField的情况下只会查询username
			queryField: ['username', 'email', 'mobile']
		});
		const {nickname,avatar}=res.userInfo||{}
		res.nickname=nickname
		res.avatar=avatar
		delete(res.userInfo)
		return res
	}
	//查找用户
	async searchUser(){
		const params=this.ctx.data
		const  serch=params.serch
		if(!serch){
			const res={
				code: 10086,
				message: "查无结果",
				msg: "查无结果"
			}
			return res
		}
		const field={
			'_id':true,
			username:true,
			avatar:true,
			nickname:true
		}
		const userList  =await this.db.collection('uni-id-users')
			.where({
				username: new RegExp(serch,'g')
			}).field(field).get()
		const res={
			code: 0,
			message: "查询成功",
			msg: "查询成功",
			userList
		}
		return res
	}
	// 登出
	async logout(){
		const res=await uniID.logout(this.ctx.data.token)
		return res
	}
	//刷新token
	async refreshToken(){
		const res=await uniID.logout(this.ctx.data.token)
		if(res.code===0){
			return await  uniID.createToken({
				uid:res.uid,
				needPermission:true
			})
		}
		this.throw('WX_OAUTH_REFRESH_TOKEN','刷新TOKEN失败')
	}
}
